<template>
  <commonformdialog :isshowDialogs="isshowDialog" :dialogTitle="dialogTitle" @closetextDialog="closeDialog" @confirmbtn="confirmbtn"
    :dialogWidth="'45%'" :topHeight='"10vh"'>
    <div class="formarea">
      <el-form ref="studentform" :model="studentforms" :rules="rules" size="small" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="学员姓名" prop="name">
              <el-input v-model="studentforms.name" placeholder="请输入学员姓名" clearable :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号" prop="tel">
              <el-input v-model="studentforms.tel" placeholder="请输入手机号" clearable :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身份证号" prop="id_card">
              <el-input v-model="studentforms.id_card" placeholder="请输入身份证号" clearable :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="招生渠道" prop="channel">
              <el-select v-model="studentforms.channel" placeholder="请选择招生渠道" clearable :style="{ width: '100%' }">
                <el-option v-for="(item, index) in channelOptions" :key="index" :label="item.title" :value="item.id"
                  :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>

          </el-col>

        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="关联机构" prop="team_id">
              <!--  <el-select v-model="studentforms.school_id" placeholder="请选择关联校区" clearable :style="{ width: '100%' }">
                <el-option v-for="(item, index) in schoolOptions" :key="index" :label="item.title" :value="item.id"
                  :disabled="item.disabled"></el-option>
              </el-select> -->
              <treeselect v-if="formType==0" v-model="studentforms.team_id" :options="treeOptions"
                :default-expand-level="1" :normalizer="normalizer" placeholder="请选择关联机构" />
              <el-cascader v-else disabled v-model="studentforms.team_id" :options="treeOptions" placeholder="请选择关联机构"
                :show-all-levels="false" :style="{ width: '100%' }" :props="{ value: 'id',label:'title',checkStrictly: true }"
                clearable></el-cascader>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="服务网点" prop="branch_id">
              <treeselect v-if="formType==0" v-model="studentforms.branch_id" :options="treeOptionsBranch"
                :default-expand-level="1" :normalizer="normalizer" placeholder="请选择服务网点" />
              <el-cascader v-else disabled v-model="studentforms.branch_id" :options="treeOptions" placeholder="请选择关联机构"
                :show-all-levels="false" :style="{ width: '100%' }" :props="{ value: 'id',label:'title',checkStrictly: true }"
                clearable></el-cascader>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="申领类型" prop="apply_type">
              <el-select v-model="studentforms.apply_type" placeholder="请选择申领类型" clearable :style="{ width: '100%' }"
                @change="changeApplyType">
                <el-option v-for="(item, index) in apply_typeOptions" :key="index" :label="item.title" :value="item.id"
                  :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="学习班型" prop="package_id">
              <el-select v-model="studentforms.package_id" :disabled="studentforms.apply_type==''" placeholder="请选择班型"
                clearable :style="{ width: '100%' }">
                <el-option v-for="(item, index) in learntypeOptions" :key="index" :label="item.title" :value="item.id"
                  :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>
          </el-col>


        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="关联教练" prop="coach_id">
              <el-select v-model="studentforms.coach_id" placeholder="请选择关联教练" clearable :style="{ width: '100%' }">
                <el-option v-for="(item, index) in coachOption" :key="index" :label="item.title" :value="item.id"
                  :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>

          </el-col>
          <el-col :span="12">

            <el-form-item label="关联场地" prop="train_place_id">
              <el-select v-model="studentforms.train_place_id" placeholder="请选择关联场地" clearable :style="{ width: '100%' }">
                <el-option v-for="(item, index) in xlcOptions" :key="index" :label="item.title" :value="item.id"
                  :disabled="item.disabled"></el-option>
              </el-select>
            </el-form-item>


          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">

            <el-form-item label="招生经办人" prop="link_man">
              <el-input v-model="studentforms.link_man" placeholder="请输入招生经办人" clearable :style="{ width: '100%' }"></el-input>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="录入时间" prop="write_time">
              <el-date-picker v-model="studentforms.write_time" format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{ width: '100%' }"
                placeholder="请选择录入时间" clearable></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="照片" prop="head_img" class="">
              <div class="">
                <uploadimg :imgModel="studentforms.head_img" class="uploaditem" @uploadimgok="head_imgok" @deleteimg='head_imgdel'>
                  <span slot="text">上传的图片大小不得超过10M</span>
                </uploadimg>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="studentforms.remark" type="textarea" placeholder="请输入备注" :autosize="{ minRows: 4, maxRows: 4 }"
                :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
  </commonformdialog>
</template>

<script>
  import commonformdialog from '@/components/commondialog/commondialog'
  //引入图片上传组件
  import uploadimg from '@/components/uploadimg/uploadimg'
  //按钮权限验证
  import checkPermission from "@/utils/permission";
  import Treeselect from "@riophae/vue-treeselect"; //下拉树组件
  //api
  import {
    createData,
    getRead,
    updateData,
  } from '@/api/student'
  import {
    getSessionStorage
  } from '@/utils/accessToken'
  //api
  import {
    readData
  } from '@/api/course'

  export default {
    data() {
      return {
        //是否禁用报名点
        isdisableenroll: false,
        studentforms: {
          name: '',
          tel: '',
          id_card: '',
          head_img: '',
          team_id: null,
          apply_type: '',
          write_time: new Date(),
          branch_id: null,
          train_place_id: '',
          link_man: '',
          channel: '',
          remark: '',
          coach_id: '',
          package_id: ''
        },
        treeOptionsBranch: [],
        rules: {
          package_id: [],
          channel: [{
            required: true,
            message: '请选择招生渠道',
            trigger: 'change',
          }, ],
          apply_type: [{
            required: false,
            message: '请选择申领类型',
            trigger: 'change',
          }, ],
          name: [{
            required: true,
            message: '请输入学员姓名',
            trigger: 'blur',
          }, ],
          tel: [{
              required: true,
              message: '请输入手机号',
              trigger: 'blur',
            },
            {
              pattern: /^1(3|4|5|7|8|9|6)\d{9}$/,
              message: '手机号格式错误',
              trigger: 'blur',
            },
          ],
          id_card: [{
              required: false,
              message: '请输入身份证号',
              trigger: 'blur',
            },
            {
              pattern: /^[1-9]\d{5}(18|19|([23]\d))\d{2}((0[1-9])|(10|11|12))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/,
              message: '身份证号码有误',
              trigger: 'blur',
            },
          ],
          head_img: [{
            required: false,
            message: '请上传照片',
            trigger: 'blur',
          }, ],
          team_id: [{
            required: false,
            message: '请选择所属机构',
            trigger: 'change',
          }, ],
          link_man: [{
            required: false,
            message: '请选择招生经办人',
            trigger: 'change',
          }, ],
          branch_id: [{
            required: false,
            message: '请选择服务网点',
            trigger: 'change',
          }, ],
          train_place_id: [{
            required: false,
            message: '请选择关联场地',
            trigger: 'change',
          }, ],
          write_time: [{
            required: true,
            message: '请选择录入时间',
            trigger: 'change',
          }, ],
          remark: [],
        },
        //选项
        schoolOptions: [],
        apply_typeOptions: [],
        bmdOptions: [],
        channelOptions: [],
        xlcOptions: [],
        treeOptions: [],
        coachOption: [],
        learntypeOptions: []
      }
    },
    components: {
      commonformdialog,
      uploadimg,
      Treeselect
    },
    props: {
      //是否显示弹窗
      isshowDialog: {
        type: Boolean,
        default: false,
        required: true,
      },
      //表单的名字
      dialogTitle: {
        type: String,
        default: '',
        required: true,
      },
      //是编辑还是新增
      formType: {
        type: Number,
        default: 0,
      },
    },
    methods: {
      normalizer(node) {
        return {
          id: node.id,
          label: node.title,
          children: node.children,
        }
      },
      //权限验证
      checkPermission,
      //删除数据
      head_imgdel() {
        this.studentforms.head_img = ''
      },
      //上传图片成功 返回图片URL
      head_imgok(imgUrl) {
        this.studentforms.head_img = imgUrl
      },
      closeDialog() {
        this.$refs['studentform'].resetFields()
        //重置表单
        this.$emit('closedialog')
      },
      //切换申领类型
      changeApplyType(e) {
        console.log(e, this.studentforms.package_id)

        this.learntypeOptions = getSessionStorage('Optionsall')['package']
        let id = e
        if (id) {
          let newOptions = [];
          this.learntypeOptions.map((item, index) => {
            if (item.apply_type.indexOf(id) != -1) {
              newOptions.push(item)
            }
          })
          this.learntypeOptions = newOptions.concat([])
        }
        let flag = false;
        this.learntypeOptions.map((item, index) => {
          if (item.id == this.studentforms.package_id) {
            flag = true;
          }
        })
        if (!flag) {
          this.studentforms.package_id = ''
        }

      },
      initData(orgList) {
        for (var i = 0; i < orgList.length; i++) {
          if (orgList[i].isBranch == 0) {
            orgList[i].isDisabled = true;
          }
          if (orgList[i].children) {
            console.log('jin')
            this.initData(orgList[i].children);
          }
        }


      },


      changeDis(obj) {

        if (obj.isBranch == 1) {
          obj.isDisabled = true;
          if (obj.children) {
            this.changeDis(obj.children)
          }
        }
      },
      confirmbtn() {
        //提交表单
        this.$refs['studentform'].validate(async (valid) => {
          if (!valid) return
          // TODO 提交表单
          let {
            name,
            tel,
            id_card,
            head_img,
            team_id,
            apply_type,
            write_time,
            branch_id,
            train_place_id,
            link_man,
            channel,
            remark,
            coach_id,
            id,
            package_id
          } = this.studentforms
          //提交的参数
          let params = {
            name,
            tel,
            id_card,
            head_img,
            team_id,
            apply_type,
            write_time,
            branch_id,
            train_place_id,
            link_man,
            channel,
            remark,
            coach_id,
            package_id
          }
          if (this.formType == 0) {
            let data = await createData(params)
            if (data.code == '0000') {
              this.$message({
                type: 'success',
                message: '新增成功!',
              })
              //清空数据
              this.$refs['studentform'].resetFields()
              //编辑和成功
              this.$emit('confirm')
            }
          } else {
            params.id = id
            params._request = 1
            let data = await updateData(params)
            if (data.code == '0000') {
              this.$message({
                type: 'success',
                message: '编辑成功!',
              })
              //清空数据
              this.$refs['studentform'].resetFields()
              //编辑和成功
              this.$emit('confirm')
            }
          }
        })
      },

    },
    mounted() {
      //选项数据
      this.schoolOptions = getSessionStorage('Optionsall')['school']
      //申领类型
      this.apply_typeOptions = getSessionStorage('Options')[1]
      //招生渠道数据
      this.channelOptions = getSessionStorage('Options')[14]
      //训练场
      this.xlcOptions = getSessionStorage('Optionsall')['train']
      //报名点
      this.bmdOptions = getSessionStorage('Optionsall')['enroll']
      //学习班型
      this.learntypeOptions = getSessionStorage('Optionsall')['package']
      this.treeOptions = getSessionStorage('Optionsall').team.concat([])
      this.treeOptionsBranch = getSessionStorage('Optionsall').team.concat([])
      // console.log(this.treeOptionsBranch ,'22222222222')
      //  var that=this
      //  this.treeOptionsBranch.forEach(item=>{
      //        console.log(item,'000000000')
      //      that.changeDis(item)
      //  })
      console.log(this.treeOptionsBranch, '00000000')
      this.initData(this.treeOptionsBranch)
      console.log(this.treeOptionsBranch, '11111111111111111')
      this.coachOption = getSessionStorage('Optionsall')['coach']
      this.$bus.on('editformStudent', async (val) => {
        //获取要编辑的id
        let id = val.id
        let data = await getRead({
          id: id
        })
        let {
          team_id,
          package_id,
          apply_type,
          enroll_data,
          branch_id,
          train_place_id,
          channel,
          coach_id
        } = data.data
        //回填数据
        this.studentforms = data.data
        this.studentforms.team_id = team_id.value
        this.studentforms.apply_type = apply_type.value
        this.studentforms.branch_id = branch_id.value
        this.studentforms.train_place_id = train_place_id.value
        this.studentforms.channel = channel.value
        this.studentforms.package_id = package_id.value
        this.studentforms.coach_id = coach_id.value
      })
    },
    destroyed() {
      this.$bus.off('editformStudent')
    },
    watch: {
      isshowDialog(val) {
        if (val) {
          //如果用户权限为normal 禁用 报名点
          if (checkPermission(['normal'])) {
            this.isdisableenroll = true
            this.studentforms.branch_id = JSON.parse(window.sessionStorage.getItem('userinfo')).enrollPoint
          }
        }
      }
    }
  }
</script>

<style scoped lang='scss'>
  .uploadimgarea {
    position: relative;

    .uploaditem {
      position: absolute;
      left: 0;
      top: 0;
    }
  }
</style>
